package com.ykdl.member.kid.fragments;

import java.util.ArrayList;

import oauth.signpost.http.HttpParameters;
import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;

import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.MessageAdapter1;
import com.ykdl.member.kid.beans.HomeMessageCount;
import com.ykdl.member.kid.beans.SystemMessageBean;
import com.ykdl.member.kid.beans.SystemMessageListBean;
import com.ykdl.member.kid.messagebox.MyMessageAcivity1;
import com.ykdl.member.kid.messagebox.OfficialMessageActivity1;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.util.RequestAsAccessTokenUtil;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.member.views.IaskMenuBarView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MessageFragment extends BaseFragment_home{

	private HomeMessageCount messageCountBean;
	private  RefreshListView main_listview ;
	private MessageAdapter1 messageadapter;
	private int start_id = 0;
	private int cursor = 0;
	private int count = 40;
	private ArrayList<SystemMessageBean>  list=new ArrayList<SystemMessageBean>();
	private HttpBaseRequest request ;
	@Override
	public View initView(LayoutInflater inflater) {
		// TODO Auto-generated method stub
		view=inflater.inflate(R.layout.mymessageacivity1_xml, null);
		inint();
		return view;
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		count = 20;
		cursor = 0;
		list=new ArrayList<SystemMessageBean>();
		super.onResume();
	}

	public void inint() {
		messageadapter = new MessageAdapter1(mContext);
		main_listview = (RefreshListView)view.findViewById(R.id.main_listview);
		main_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				SystemMessageBean bean= (SystemMessageBean)messageadapter.getItem(arg2);
				Intent intent = new Intent(mContext,OfficialMessageActivity1.class);
				intent.putExtra(KidAction.MESSAGE_ID, bean.getLast().getFrom_actor().getActor_id()+"");
				intent.putExtra(KidAction.TITLE_NAME, bean.getLast().getFrom_actor().getDisplay_name()+"");
//				MyMessageAcivity.this.startActivity(intent);
				startActivityForResult(intent, 100);  
			}
		});
		main_listview.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				count = 20;
				cursor = 0;
				list=new ArrayList<SystemMessageBean>();
				getSystemMessage();
				initMessageCount();
			}
			});
		main_listview.setMoreClick(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getSystemMessage();
			}});
		
		
		if(hasUnknowinfo()){      //有未读消息
			if (red_point!=null) {
				red_point.setVisibility(view.VISIBLE);
			}
			//重新拿一下数据
//			count = 20;
//			cursor = 0;
//			list=new ArrayList<SystemMessageBean>();
//			getSystemMessage();
//			return;
		}else{
			if (red_point!=null) {
				red_point.setVisibility(view.GONE);
			}
		}
		getSystemMessage();
	}
	//如果有未读的消息，点击消息导航图标时调用此方法刷新messageFragment
	public void refreshMessageFragment(){
		if(hasUnknowinfo()){
			count = 20;
			cursor = 0;
			list=new ArrayList<SystemMessageBean>();
			getSystemMessage();
		}
	}
	/**
	 * 从本地文件读是否有未读信息
	 * @return
	 */
	public boolean hasUnknowinfo(){    
		String unknownInfo=MyPrefs.getMessageCount(mContext);  //从本地文件中取
		if(!TextUtils.isEmpty(unknownInfo) && unknownInfo.equals("1")){
			return true;
		}
		return false;
	}
	
	public void deltnewsList(String group){
		String pageurl=KidConfig.DELT_SYSTEMMESSAGE_LIST;
		HttpParameters bodyParams = new HttpParameters();
		bodyParams.put("group", group);
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl, bodyParams,"");
		TaskManager.startHttpRequest(request, null, null);
	}
	
	public void getSystemMessage() {
//		showProgress("正在加载中,请稍等...");
		String  pageurl =KidConfig.NEWS_INDEX;
		HttpParameters parameterss = new HttpParameters();
		parameterss.put("start_id", String.valueOf(start_id));
		parameterss.put("cursor", String.valueOf(cursor));
		parameterss.put("count", String.valueOf(count));
		HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl, parameterss,"");
		 TaskManager.startHttpRequest(request, new getSystemMessageTag(),  SystemMessageListBean.class);
	}

	class getSystemMessageTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof SystemMessageListBean) {
				SystemMessageListBean bean =(SystemMessageListBean)t;
				if(null==bean.getError()){
					if (bean.getList().size()>0) {
						for (SystemMessageBean obj : bean.getList()) {
							list.add(obj);
						}
						messageadapter.setlist(list);
						main_listview.setAdapter(messageadapter);
						main_listview.setVisibility(View.VISIBLE);
						messageadapter.notifyDataSetChanged();
						hidErrorTip( );
						if (bean.getNext_cursor() == bean.getTotal_number()) {
							main_listview.setMoreButtoIsGon(true);
						} else {
							cursor = bean.getNext_cursor();
							main_listview.setMoreButtoIsGon(false);
						}
					}else {
						main_listview.setVisibility(View.GONE);
						showErrorTip("没有数据","");
					}
					main_listview.onRefreshComplete();
					main_listview.setFecthMoreOk();
				}else {
					Toast.makeText(mContext, "失败,"+bean.getDesc(), 1).show();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			main_listview.onRefreshComplete();
			main_listview.setFecthMoreOk();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
	}
	
	 private void initMessageCount() {
			String url = KidConfig.UNREAD_NEWS_COUNT ;
			HttpParameters bodyParams = new HttpParameters();
			request = Wxxr.getInstance().postBaseRequest(url, bodyParams,null
					);
			TaskManager.startHttpRequest(request, new getMessageCountTag(),
					HomeMessageCount.class);
		}
	 class getMessageCountTag implements ITag{
			@Override
			public void refreshUI(Object t, DataState ds) {
				if(null != t && t instanceof HomeMessageCount){
				    messageCountBean = (HomeMessageCount)t;
					if(messageCountBean.isExpired()){
						RequestAsAccessTokenUtil.getInstance(mContext).refreshTokenRequest(request, this, HomeMessageCount.class);
					}else{
						
					 settingMessageCount();
					}
				}
			}
			
			/**
			 * 设置信息数量汇总
			 */
			public void settingMessageCount() {
				if (messageCountBean.getUnread_count() > 0) {
					red_point.setVisibility(view.VISIBLE);
					MyPrefs.setMessageCount(mContext, "1");
				}else {
					red_point.setVisibility(view.GONE);
					MyPrefs.setMessageCount(mContext, null);
				}
			}


			@Override
			public boolean refreshError(DataParseError parseError) {
				return true;
			}

			@Override
			public void refreshCancel() {
			}
			
		}
	 
	  @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
			// TODO Auto-generated method stub
			super.onActivityResult(requestCode, resultCode, data);
			if(requestCode==100 && resultCode==100){
				//重新读取网络数据，判断是否有未读的消息
				list=new ArrayList<SystemMessageBean>();
				initMessageCount();
				getSystemMessage();
				
//				HomeMessageCount hc=new HomeMessageCount();
//				if(hc.getUnread_count()>0){
//					iask_menu_bar.setMessageBar(false);
//				}else{
//					iask_menu_bar.setSelectedID(R.id.bar_personnews);
//				}
				
			}
		}
	
	 
	@Override
	public void initData(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
	}

}
